import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { workAPI, userAPI } from '../services/api';
import './styles.css';

function ArticleDetail() {
  const [article, setArticle] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [authorInfo, setAuthorInfo] = useState(null);
  const [authorLoading, setAuthorLoading] = useState(false);
  
  const { workId } = useParams();
  const navigate = useNavigate();

  // 在组件加载时获取文章详情
  useEffect(() => {
    fetchArticleDetail();
  }, [workId]);

  // 获取文章详情
  const fetchArticleDetail = async () => {
    try {
      setLoading(true);
      const workInfoId={
        workId:String(workId),
        userId:"1"
      }
      const response = await workAPI.getWorkDetail(workInfoId);
      
      if (response && response.result) {
        setArticle(response.result);
        
        // 如果文章存在作者ID，则获取作者信息
        if (response.result.userId) {
          fetchAuthorInfo(response.result.userId);
        }
      } else {
        setError('文章不存在或已被删除');
      }
    } catch (err) {
      console.error('获取文章详情失败:', err);
      setError('获取文章详情时发生错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 返回首页
  const goBack = () => {
    navigate('/');
  };

  // 获取作者信息
  const fetchAuthorInfo = async (userId) => {
    try {
      setAuthorLoading(true);

      console.log('获取作者信息，参数:', { userId: String(userId) });
      const response = await userAPI.getUserInfo({ userId: String(userId) });
    console.log('获取作者信息，返回:', response);
      if (response && response.result) {
        setAuthorInfo(response.result);
        console.log('作者信息:', response.result);
      }
    } catch (err) {
      console.error('获取作者信息失败:', err);
      // 获取作者信息失败不显示错误，只是不显示作者信息
    } finally {
      setAuthorLoading(false);
    }
  };

  // 格式化日期显示
  const formatDate = (dateString) => {
    if (!dateString) return '未知日期';
    
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', { 
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <div className="article-detail-container">
      <header className="article-detail-header">
        <button className="back-button" onClick={goBack}>返回首页</button>
        <h1 className="clickable" onClick={goBack}>Board Demo</h1>
        <div></div> {/* 占位以保持标题居中 */}
      </header>

      <div className="article-detail-content">
        {loading ? (
          <div className="loading">加载中...</div>
        ) : error ? (
          <div className="error-message">{error}</div>
        ) : article ? (
          <div className="article-full">
            <h1 className="article-full-title">{article.title}</h1>
            
            <div className="article-author">
              {authorLoading ? (
                <span>作者信息加载中...</span>
              ) : authorInfo ? (
                <span>
                  作者：
                  <span 
                    className="author-link clickable" 
                    onClick={() => navigate(`/author/${article.userId}`)}
                  >
                    {authorInfo.nickName || '未知用户'}
                  </span>
                </span>
              ) : (
                <span>作者：未知</span>
              )}
            </div>
            
            <div className="article-full-meta">
              <span>发布时间：{formatDate(article.createdAt)}</span>
            </div>
            
            {article.description && (
              <div className="article-full-description">
                <strong>简介：</strong> {article.description}
              </div>
            )}
            
            <div className="article-full-body">
              {article.context ? (
                <div dangerouslySetInnerHTML={{ __html: article.context.replace(/\n/g, '<br>') }} />
              ) : (
                <p>文章内容为空</p>
              )}
            </div>
          </div>
        ) : (
          <div className="no-article">文章不存在</div>
        )}
      </div>
    </div>
  );
}

export default ArticleDetail;
